package com.imddy.gkrpc.transport;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.servlet.ServletContextHandler;
import org.eclipse.jetty.servlet.ServletHolder;

import lombok.extern.slf4j.Slf4j;

@Slf4j
public class HttpTransportServer implements TransportServer {
	
	private RequestHandler handler;
	private Server server;

	@Override
	public void init(int port, RequestHandler requestHandler) {
		this.handler = requestHandler;
		this.server = new Server(port);
		
		// servlet
		ServletContextHandler ctxHandler = new ServletContextHandler();
		server.setHandler(ctxHandler);
		
		ServletHolder holder = new ServletHolder(new RequestServlet());
		ctxHandler.addServlet(holder, "/*");
	}

	@Override
	public void start() {
		// TODO Auto-generated method stub
		try {
			server.start();
			server.join();
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}

	}

	@Override
	public void stop() {
		// TODO Auto-generated method stub
		try {
			server.stop();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	class RequestServlet extends HttpServlet {
		@Override
		protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
			// TODO Auto-generated method stub
			log.info("client connect.");
			InputStream in = req.getInputStream();
			OutputStream out = resp.getOutputStream();
			if (handler != null) {
				handler.onHandler(in, out);
			}
			out.flush();
		}
	}

}
